import { actionManager } from "@/action/ActionManager";
import ContextMenu from "@/common/ContextMenu/index.vue";
import { rmi } from "@/util/IpcWindow/RMI";
import { ipcRenderer } from "electron";
import { IpcMsg, WindowName } from "@/mdesign-lib/mdesign-main.js";
import { ModelFrom } from "@/constants/Enums";
import { ModelData } from "@/constants/types";
import { ActionKey } from "@/action/ActionKey";
import { SelectOnTreeAction } from "@/modules/model/actions/common/SelectOnTreeAction";
export const propertyModelContextMenu = async (event: MouseEvent, model: ModelData) => {
  if (!app.activeProject || !model) return;
  if (!model.visible) return;
  ContextMenu.popup({
    x: event.clientX,
    y: event.clientY,
    menuItems: [
      {
        label: "树上高亮",
        key: "selectOnTree",
        // keyboard: 'SHORTCUTKEY: Alt+B',
        showLabel: false,
        editType: "button",
        icon: "statics/icons/table/showModelPosition.svg"
      }
    ]
  })
    .then(async (menuItem: any) => {
      const needConfirm = await checkNeedConfirm(model);
      if (needConfirm) {
        const ok = await popConfirm();

        if (!ok) {
          return;
        }
      }

      if (app.global.isIpcWindow) {
        await rmi.invokeAction(menuItem.key, [
          [model.id],
          { scroll: true, changeTab: true, isModelLibrary: false, modelLibraryProjectId: "", skipConfirm: true }
        ]);
        ipcRenderer.send(IpcMsg.WindowFocus, WindowName.MainWindow); //  向主窗口发送消息，将主窗口激活
      } else {
        const selectOnTreeAction = actionManager.getAction(ActionKey.selectOnTree) as SelectOnTreeAction;
        await selectOnTreeAction.run([model.id], {
          scroll: true,
          changeTab: true,
          isModelLibrary: false,
          modelLibraryProjectId: "",
          skipConfirm: true
        });
      }
    })
    .catch((e: any) => {
      e && console.error(e);
    });
};

export async function checkNeedConfirm(model: ModelData) {
  if (app.global.isIpcWindow) {
    if (model.from === ModelFrom.USER_CREATE) {
      return false;
    } else {
      const showProfileOnModelTree = await rmi.query("app.activeProject.ui.showProfileOnModelTree");
      if (showProfileOnModelTree) {
        return false;
      } else {
        return true;
      }
    }
  } else {
    const project = app.projectManager.getProject(model.projectId);
    if (model.from === ModelFrom.USER_CREATE || project?.ui.showProfileOnModelTree) {
      return false;
    } else {
      return true;
    }
  }
}

export async function popConfirm() {
  const ok = await app.$confirm
    .popup({
      title: "提示",
      subTitle: "文件已被隐藏，是否显示扩展文件？",
      showCheckbox: false,
      status: "warn"
    })
    .catch(() => false);
  return ok;
}
